<template>
  <!-- 充电桩 详细信息 -->
  <div class="countContainer">
    <div
      class="countItem"
      v-for="(item, index) in countItems"
      :key="index"
      :ref="(el) => setItemRef(el, index)"
    >
      <canvas :ref="(el) => setCanvasRef(el, index)" class="particle-canvas" />
      <div class="countCircle">
        <div class="countValue">
          <span class="countNumber">{{ item.value }}</span>
          <span class="countIcon">{{ item.unit }}</span>
        </div>
      </div>
      <div class="countLabel">{{ item.label }}</div>
    </div>
  </div>
</template>

<script setup>
;

const props = defineProps({
  toltalCount: {
    type: Object,
    default: () => ({})
  }
});
const $api = inject("$api");

// 数据
const stationCount = ref(0);
const pileCount = ref(0);
const gunCount = ref(0);
const totalCharge = ref(0);
const serviceCount = ref(0);
watch(
  () => props.toltalCount,
  (newVal) => {
    if (newVal) {
      stationCount.value = newVal.stationTotal || 0;
      pileCount.value = newVal.pileTotal || 0;
      gunCount.value = newVal.gunTotal || 0;
      totalCharge.value = newVal.electricity || 0;
      serviceCount.value = newVal.orderNum || 0;
    }
  }
);
const countItems = computed(() => [
  { value: stationCount.value, unit: "个", label: "充电站总数" },
  { value: pileCount.value, unit: "个", label: "充电桩总数" },
  { value: gunCount.value, unit: "个", label: "充电枪总数" },
  { value: totalCharge.value, unit: "", label: "累计充电量kWh" },
  { value: serviceCount.value, unit: "次", label: "累计服务次数" },
]);

const itemRefs = ref([]);
const canvasRefs = ref([]);

// 设置引用
const setItemRef = (el, index) => {
  if (el) itemRefs.value[index] = el;
};

const setCanvasRef = (el, index) => {
  if (el) canvasRefs.value[index] = el;
};

// 创建粒子函数
const createParticle = (canvas, options) => {
  const ctx = canvas.getContext("2d");
  const particle = {
    canvas,
    ctx,
    x: Math.random() * canvas.width,
    y: Math.random() * canvas.height,
    size: Math.random() * 3 + 1,
    speedX: Math.random() * 1 - 0.5,
    speedY: Math.random() * 1 - 0.5,
    color: options.color || "#22f2ff",
    alpha: Math.random() * 0.3,
    maxAlpha: 0,

    update() {
      this.x += this.speedX;
      this.y += this.speedY;

      // 边界检测
      if (this.x > this.canvas.width || this.x < 0) {
        this.speedX = -this.speedX;
      }

      if (this.y > this.canvas.height || this.y < 0) {
        this.speedY = -this.speedY;
      }

      // 随机闪烁效果
      this.alpha += (Math.random() - 0.5) * 0.03;
      if (this.alpha < 0.1) this.alpha = 0.1;
      if (this.alpha > this.maxAlpha) this.alpha = this.maxAlpha;
    },

    draw() {
      this.ctx.beginPath();
      this.ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
      this.ctx.fillStyle =
        this.color +
        Math.floor(this.alpha * 255)
          .toString(16)
          .padStart(2, "0");
      this.ctx.fill();
    },
  };

  particle.maxAlpha = particle.alpha;
  return particle;
};

// 创建粒子系统函数
const createParticleSystem = (canvas, options = {}) => {
  const ctx = canvas.getContext("2d");
  const system = {
    canvas,
    ctx,
    particles: [],
    particleCount: options.count || 20,
    color: options.color || "#22f2ff",
    animationId: null,

    init() {
      // 创建粒子
      for (let i = 0; i < this.particleCount; i++) {
        this.particles.push(createParticle(this.canvas, { color: this.color }));
      }
    },

    animate() {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

      // 更新并绘制所有粒子
      for (const particle of this.particles) {
        particle.update();
        particle.draw();
      }

      // 连接临近粒子
      this.connectParticles();

      this.animationId = requestAnimationFrame(this.animate.bind(this));
    },

    connectParticles() {
      const maxDistance = 80;

      for (let i = 0; i < this.particles.length; i++) {
        for (let j = i + 1; j < this.particles.length; j++) {
          const dx = this.particles[i].x - this.particles[j].x;
          const dy = this.particles[i].y - this.particles[j].y;
          const distance = Math.sqrt(dx * dx + dy * dy);

          if (distance < maxDistance) {
            // 根据距离计算线条透明度
            const alpha = 1 - distance / maxDistance;

            this.ctx.beginPath();
            this.ctx.strokeStyle =
              this.color +
              Math.floor(alpha * 50)
                .toString(16)
                .padStart(2, "0");
            this.ctx.lineWidth = 0.5;
            this.ctx.moveTo(this.particles[i].x, this.particles[i].y);
            this.ctx.lineTo(this.particles[j].x, this.particles[j].y);
            this.ctx.stroke();
          }
        }
      }
    },

    start() {
      this.animate();
    },

    stop() {
      if (this.animationId) {
        cancelAnimationFrame(this.animationId);
        this.animationId = null;
      }
    },

    resize(width, height) {
      this.canvas.width = width;
      this.canvas.height = height;
    },
  };

  system.init();
  return system;
};

// 存储粒子系统实例
const particleSystems = ref([]);

// 初始化Canvas和粒子系统
const initParticles = () => {
  nextTick(() => {
    // 清理旧的粒子系统
    particleSystems.value.forEach((system) => system.stop());
    particleSystems.value = [];
    // 为每个countItem创建粒子系统
    canvasRefs.value.forEach((canvas, index) => {
      if (!canvas) return;
      const item = itemRefs.value[index];
      if (!item) return;
      canvas.width = item.offsetWidth;
      canvas.height = item.offsetHeight;
      const system = createParticleSystem(canvas, {
        count: 8,
        color: "#22f2ff",
      });
      system.start();
      particleSystems.value.push(system);
    });
  });
};

const handleResize = () => {
  initParticles();
};


onMounted(() => {
  initParticles();
  window.addEventListener("resize", handleResize);
});

onBeforeUnmount(() => {
  // 清理粒子系统和事件监听
  particleSystems.value.forEach((system) => system.stop());
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped lang="less">
.countContainer {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
}

.countItem {
  display: flex;
  height: 140px;
  flex-direction: column;
  align-items: center;
  text-align: center;
  background: url("@/assets/screen/itemBase.png") no-repeat center bottom /
    contain;
  margin-right: 15px;
  position: relative;
  overflow: hidden;
  &:last-child {
    margin-right: 0;
  }
}

.particle-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.countCircle {
  width: 170px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-bottom: 15px;
  position: relative;
  z-index: 2;
}

.countValue {
  display: flex;
  align-items: baseline;
  justify-content: center;
}

.countNumber {
  font-size: 36px;
  font-weight: bold;
  color: #22f2ff;
  line-height: 1;
  text-shadow: 0 0 10px rgba(34, 242, 255, 0.3);
}

.countIcon {
  color: #fff;
  font-size: 12px;
  margin-left: 5px;
}
.countLabel {
  font-size: 18px;
  color: #fff;
  text-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
  position: relative;
  z-index: 2;
}

@media (max-width: 1500px) {
  .countCircle {
    width: 120px;
  }
  .countNumber {
    font-size: 26px;
  }
  .countIcon {
    font-size: 10px;
  }
  .countLabel {
    font-size: 16px;
  }
  .countItem {
    height: 125px;
    width: 136px;
    margin-right: 0px;
  }
}
</style>
